#pragma once
#include <iostream>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h> // 包含sockaddr_in结构体和相关常量
#include <arpa/inet.h>  // 包含IP地址转换函数
class server
{
public:
    server(std::string ip,std::string port)
    :_port(port)
    ,_ip(ip)
    ,sockfd(-1)
    {
    }
    ~server()
    {
    }
    void Init()
    {
        int ret = socket(AF_INET, 0, SOCK_DGRAM);
        if (ret < 0)
        {
            std::cout << "socket fail!" << std::endl;
            exit(1);
        }
        sockfd = ret;

        struct sockaddr_in local;
        struct in_addr addr;
        inet_pton(AF_INET, _ip.c_str(), &addr);
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(std::stoi(_port.c_str()));
        local.sin_addr=addr;

        socklen_t len=sizeof(local);
        int n=bind(sockfd,(struct sockaddr*)&local,len);
        if(bind<0)
        {
            std::cout<<"bind fail!"<<std::endl;
        }
    }
    void Start()
    {
        while(1)
        {
            char buffer[1024];
            struct sockaddr_in peer;
            socklen_t len=sizeof(peer);
            int n=recvfrom(sockfd,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&peer,&len);
            if(n<0)
            {
                std::cout<<"recvfrom fail!"<<std::endl;
                return;
            }
            buffer[n]='0';
            std::cout<<"client say:"<<buffer<<std::endl;
            std::string messager="echoserver# ";
            messager+=buffer;
            int ret=sendto(sockfd,messager.c_str(),messager.size(),0,(const struct sockaddr*)&peer,len);
            if(ret<0)
            {
                std::cout<<"sendto fail!"<<std::endl;
            }
        }
    }

private:
    std::string _ip;
    int sockfd;
    std::string _port;
};